<template>
	<view class="wanl-order-list">
		<view class="navbar">
			<view class="nav-item text-df" v-for="(item, index) in navList" :key="item.state"
				:class="{ current: tabCurrentIndex === index }" @tap="tabClick(index)">
				{{ item.text }}
			</view>
		</view>
		<swiper :current="tabCurrentIndex" style="height: calc(100% - 80rpx)" duration="300" @change="changeTab">
			<swiper-item class="tab-content" v-for="(tag, key) in navList" :key="tag.state">
				<scroll-view class="list-scroll-content" scroll-y @scrolltolower="loadData">
					<!-- 空白页 -->
					<wanl-empty text="没有找到任何订单" v-if="tag.loaded === true && tag.orderList.length === 0" />
					<!-- 订单列表 -->
					<view v-for="(order, okey) in tag.orderList" :key="okey" class="order-item radius-bock">
						<view class="head">
							<view class="shop wanl-gray">
								<!-- <text class="wlIcon-dianpu1 wanl-black"></text> -->订单编号：
								<text class="wanl-black margin-lr-xs text-30">{{ order.order_num }}</text>
								<!-- <text class="wlIcon-fanhuigengduo text-sm"></text> -->
							</view>

							<view class="margin-right-bj text-sm">
								<!-- <text class="state" :style="{ color: order.stateTipColor }">{{ order.stateTip }}</text> -->
								<text v-if="order.status === -1" class="margin-left-sm wlIcon-lajitong"
									@tap="deleteOrder(order.id,okey)"></text>
							</view>
						</view>
						<!-- 商品 -->
						<view class="goods-box" v-for="(goods, gkey) in order.good" :key="goods.id"
							@tap="orderDetails(order.id)">
							<view class="cu-avatar xl margin-right-bj radius"
								:style="{backgroundImage: 'url('+$wanlshop.oss(goods.cover, 70, 70)+')'}"> </view>
							<view class="content margin-right-bj">
								<view class="describe">
									<view class="text-cut-2">
										{{goods.good_title}}
									</view>
									<view class="wanl_sku text-min" v-if="goods.good_sku">
										<text class="wanl-gray-dark">{{goods.good_sku}}</text>
									</view>
								</view>
								<view class="parameter">
									<view class="text-price text-sm text-black">
										{{price_format('yuan',goods.good_price)}}.{{price_format('fen',goods.good_price)}}
									</view>
									<view class="text-min wanl-gray">
										x {{ goods.good_num }}
									</view>
									<!-- 退款状态:0=未退款,1=退款中,2=待退货,3=退款完成 -->
									<!-- <view class="text-min text-yellow" v-if="goods.refund_status != 0">
										{{getRefund(goods.refund_status)}}
									</view> -->
								</view>
							</view>
						</view>
						<!-- 底部 -->
						<view class="price-box text-sm flex">
							<!-- <view v-if="order.pay.discount_price > 0" class="margin-right-sm wanl-gray">优惠：<text
									class="text-price">{{ order.pay.discount_price }}</text></view> -->
							<!-- <view v-if="order.ship_price > 0" class="margin-right-sm wanl-gray">快递：<text
									class="text-price">{{ order.ship_price}}</text></view> -->
							<view>实付款：<text
									class="text-price">{{price_format('yuan',order.pay_price)}}.{{price_format('fen',order.pay_price)}}</text>
							</view>
						</view>
						<view class="action-box padding-bottom-bj" v-if="order.status == '0'">
							<!-- <button class="cu-btn round line-black margin-lr-bj"
								@tap="editAddress(order.id)">修改地址</button> -->
							<button class="cu-btn round line-black" @tap="cancelOrder(order,okey)">取消订单</button>
							<button class="cu-btn round margin-lr-bj wanl-bg-orange"
								@tap="paymentOrder(order)">去付款</button>
							<!-- <button class="cu-btn round line-black" @tap="reorder(order.id,order.store_id)">再来一单</button> -->
						</view>
						<!-- <view class="action-box padding-bottom-bj" v-if="order.status == '10'">
							<button class="cu-btn round line-black" @tap="toChat(order.shop_id)">联系商家</button>
							<button class="cu-btn round margin-lr-bj wanl-bg-orange"
								@tap="editAddress(order.id)">修改地址</button>
						</view> -->
						<view class="action-box padding-bottom-bj" v-if="order.status == '20'">
							<button class="cu-btn round margin-lr-bj line-black" @tap="reorder(order.id,order.store_id)">再来一单</button>
							<button class="cu-btn round line-black" @tap="onLogistics(order.id)">查看物流</button>
							<button class="cu-btn round margin-lr-bj wanl-bg-orange"
								@tap="confirmOrder(order,okey)">确认收货</button>
							</view>
						<view class="action-box padding-bottom-bj" v-if="order.status == '30'">
							<button class="cu-btn round margin-lr-bj line-black" @tap="reorder(order.id,order.store_id)">再来一单</button>
							<button class="cu-btn round line-black" @tap="deleteOrder(order.id,okey)">删除订单</button>
							<button class="cu-btn round margin-lr-bj line-black" @tap="commentOrder(order)">去评价</button>
							
						</view>
						<view class="action-box padding-bottom-bj" v-if="order.status == '-1'">
							<button class="cu-btn round margin-lr-bj line-black" @tap="reorder(order.id,order.store_id)">再来一单</button>
							<button class="cu-btn round line-black" @tap="deleteOrder(order.id,okey)">删除订单</button>
							
						</view>
						<view class="action-box padding-bottom-bj" v-if="order.status == '40'">
							<button class="cu-btn round margin-lr-bj line-black" @tap="reorder(order.id,order.store_id)">再来一单</button>
							<button class="cu-btn round line-black" @tap="deleteOrder(order.id,okey)">删除订单</button>
						</view>
					</view>
					<uni-load-more :status="tag.loadingType" :content-text="contentText" />
					<view class="edgeInsetBottom"></view>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tabCurrentIndex: 0,
				navList: [{
						status: 'all',
						state: 0,
						text: '全部',
						loadingType: 'more',
						current_page: 1,
						orderList: []
					},
					{
						status: 0,
						state: 1,
						text: '待支付',
						loadingType: 'more',
						current_page: 1,
						orderList: []
					},
					{
						status: 10,
						state: 2,
						text: '待发货',
						loadingType: 'more',
						current_page: 1,
						orderList: []
					},
					{
						status: 20,
						state: 3,
						text: '待收货',
						loadingType: 'more',
						current_page: 1,
						orderList: []
					},
					{
						status: 30,
						state: 4,
						text: '待评论',
						loadingType: 'more',
						current_page: 1,
						orderList: []
					}, {
						status: 40,
						state: 7,
						text: '已退款',
						loadingType: 'more',
						current_page: 1,
						orderList: []
					}
				],
				contentText: {
					contentdown: ' ',
					contentrefresh: '正在加载...',
					contentnomore: ''
				}
			};
		},
		onLoad(options) {
			if (!options.state) {
				options.state = 0;
			}
			this.tabCurrentIndex = +options.state;
			// #ifndef MP
			this.loadData();
			// #endif
			// #ifdef MP
			if (options.state == 0) {
				this.loadData();
			}
			// #endif
		},
		methods: {
			// 立即付款
			price_format: function(type, price) {

				var price = (price / 100).toFixed(2);
				var status = (price + '').indexOf('.')
				// console.log(status)
				if (status == '-1') {
					if (type == 'yuan') {
						// console.log(price)
						return price;
					}
					if (type == 'fen') {
						return '00';
					}
				}
				var price_array = (price + '').split('.')
				if (type == 'yuan') {
					return price_array[0];
				}
				if (type == 'fen') {
					var price_fen = price_array[1].length < 2 ? price_array[1] + '0' : price_array[1];
					return price_fen;
				}
			},
			//获取订单列表
			async loadData(source) {
				//这里是将订单挂载到tab列表下
				let index = this.tabCurrentIndex;
				let navItem = this.navList[index];
				let state = navItem.state;
				let status = navItem.status;
				//判断是否最后一页
				if (navItem.loadingType == 'noMore') {
					return;
				}
				//tab切换只有第一次需要加载数据
				if (source === 'tabChange' && navItem.loaded === true) {
					return;
				}
				//防止重复加载
				if (navItem.loadingType === 'loading') {
					return;
				}
				navItem.loadingType = 'loading';
				// 获取列表
				await uni.request({
					url: '/api/Order/orderList',
					data: {
						state: state,
						page: navItem.current_page,
						token: uni.getStorageSync("wanlshop:user").token,
						status: status,
					},
					success: res => {
						navItem.current_page = res.data.current_page; //当前页码
						if (res.data.length < 20) {
							navItem.loadingType = 'noMore';
						} else {
							navItem.loadingType = 'more';
							navItem.current_page++;
						}
						  console.log(JSON.stringify(res.data, null, 2)); // 美化输出
						let orderList = res.data;
						// let orderList = res.data.filter(item => {
						// 	//添加不同状态下订单的表现形式
						// 	item = Object.assign(item, this.orderStateExp(item.status));
						// 	//演示数据所以自己进行状态筛选
						// 	if (status === 0) {
						// 		//0为全部订单
						// 		return item;
						// 	}
						// 	return item.status === status;
						// });
						orderList.forEach(item => {
							navItem.orderList.push(item);
						});
						//loaded新字段用于表示数据加载完毕，如果为空可以显示空白页
						this.$set(navItem, 'loaded', true);
					}
				});
			},

			//swiper 切换
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
				this.loadData('tabChange');
			},
			//顶部tab点击
			tabClick(index) {
				this.tabCurrentIndex = index;
			},
			//删除订单
			async deleteOrder(order_id, key) {
				uni.showLoading({
					title: '请稍后'
				});

				uni.showModal({
					title: '提示',
					content: '确定删除订单吗？',
					cancelText: "取消", // 取消按钮的文字  
					confirmText: "确认", // 确认按钮的文字  
					showCancel: true, // 是否显示取消按钮，默认为 true
					confirmColor: '#f55850',
					cancelColor: '#39B54A',
					success: (res) => {
						if (res.confirm) {
							console.log('comfirm') //点击确定之后执行的代码

							uni.request({
								url: '/api/Order/delOrder',
								method: 'POST',
								data: {
									order_id: order_id,
									token: uni.getStorageSync("wanlshop:user").token,
								},
								success: res => {
									this.navList[this.tabCurrentIndex].orderList.splice(key,
									1);
									uni.showToast({
										title: '删除成功'
									})
									uni.hideLoading();
								}
							});

						} else {
							console.log('cancel') //点击取消之后执行的代码
						}
					}
				})


			},
			//取消订单- 设置为7 -全局
			async cancelOrder(item, key) {
				// uni.showLoading({
				// 	title: '请稍后'
				// });

				uni.showModal({
					title: '提示',
					content: '确定取消订单吗？',
					cancelText: "取消", // 取消按钮的文字  
					confirmText: "确认", // 确认按钮的文字  
					showCancel: true, // 是否显示取消按钮，默认为 true
					confirmColor: '#f55850',
					cancelColor: '#39B54A',
					success: (res) => {
						if (res.confirm) {
							console.log('comfirm') //点击确定之后执行的代码
							// 获取列表
							uni.request({
								url: '/api/Order/cancelOrder',
								method: 'POST',
								data: {
									order_id: item.id,
									token: uni.getStorageSync("wanlshop:user").token,
								},
								success: res => {
									
									this.navList[this.tabCurrentIndex].orderList.splice(key,
									1);
									// let {
									// 	stateTip,
									// 	stateTipColor
									// } = this.orderStateExp(7);
									// item = Object.assign(item, {
									// 	state: 7,
									// 	stateTip,
									// 	stateTipColor
									// });
									// this.$store.commit('statistics/order', {
									// 	pay: this.$store.state.statistics.order.pay -
									// 		1,
									// 	whole: this.$store.state.statistics.order
									// 		.whole - 1
									// });
									// 取消订单后删除待付款中该项，并修改全部中的状态 1.0.2升级
									// let list = this.navList[1].orderList;
									// let index = list.findIndex(val => val.id === item.id);
									// index !== -1 && list.splice(index, 1);
									// // 删除后修改全部中的为7
									// if (this.tabCurrentIndex == 1) {
									// 	let list = this.navList[0].orderList;
									// 	let index = list.findIndex(val => val.id === item.id);
									// 	if (index !== -1) {
									// 		list[index].state = 7;
									// 	}
									// }
									uni.showToast({
										title: '取消成功'
									})
									// uni.hideLoading();
								}
							});
						} else {
							console.log('cancel') //点击取消之后执行的代码
						}
					}
				})


			},
			commentOrder(data) {
				// console.log(data.id)
				var comment = [];
				data.good.forEach(function(el) {
					var obj = {
						good_id: el.good_id,
						good_name: el.title + ' ' + el.good_sku,
						star_num: 5,
						content: "",
						good_img: el.cover,
						good_sku: el.good_sku,
						img: [],
						imgpath: []
					}
					comment.push(obj)
				})
				// console.log(comment)

				uni.setStorageSync("goods_comment1", comment);

				// uni.setStorage('id', data.id);

				this.$wanlshop.to(`/pages/user/order/comment?order_id=${data.id}&data=${JSON.stringify(comment)}`);
			},
			reorder(order_id,store_id) {
				let city_name = uni.getStorageSync("city_name");
				uni.request({
					url: '/api/GoodCart/reorder',
					method: 'POST',
					data: {
					  token: uni.getStorageSync("wanlshop:user").token,
					  order_id: order_id,
					  city_name:city_name,
					  store_id:store_id,
					},
			    success: res => {
					  console.log(JSON.stringify(res, null, 2)); // 美化输出
					if (res.data && res.data.status === 6) { // 检查res.data是否存在
					  uni.showModal({
					    title: '提示',
					    content: res.data.msg || '发生未知错误',
					    showCancel: false
					  });
					} else if (res.res && res.res.status === 1) { // 检查res.res是否存在
					  uni.showModal({
					    title: '提示',
					    content: res.res.msg || '操作成功',
					    showCancel: false,
					    success: (modalRes) => {
					      if (modalRes.confirm) {
					        uni.switchTab({
					          url: '/pages/cart'
					        });
					      }
					    }
					  });
					} else {
					  uni.showToast({
					    title: res.data?.msg || res.res?.msg || '请求失败',
					    icon: 'none'
					  });
					}

			    }
			  });
			},

			//支付订单
			paymentOrder(data) {
				// console.log(777)
				// alert(data.pay_price)
				let lists = []
				lists.push({
					goods_id: data.good.good_id,
					number: data.good.good_num,
					sku_id: data.sku_id,
					good_price: data.good_price/100,
					ship_price:data.ship_price/100,
					freight_price:data.freight_price/100,
					order_no: data.order_num,
					order_id: data.id,
				});
				// alert(JSON.stringify(lists))
				this.$wanlshop.to(`/pages/user/money/pay?order_id=${data.id}&data=${JSON.stringify(lists)}&amount=`+data.pay_price/100);
			},
			//确认收货- 全局
			async confirmOrder(item,index) {
				
				uni.showLoading({
					title: '请稍后'
				});
				// 获取列表
				await uni.request({
					url: '/api/Order/confirmOrder',
					method: 'POST',
					data: {
						order_id: item.id,
						token: uni.getStorageSync("wanlshop:user").token
					},
					success: res => {
						let {
							stateTip,
							stateTipColor
						} = this.orderStateExp(4);
						item = Object.assign(item, {
							status:30,
							state: 4,
							stateTip,
							stateTipColor
						});
						
						
						// this.$store.commit('statistics/order', {
						// 	receiving: this.$store.state.statistics.order.receiving - 1,
						// 	evaluate: this.$store.state.statistics.order.evaluate + 1
						// });
						this.$wanlshop.msg('确认成功')
						// this.loadData();
						// uni.hideLoading();
					}
				});
			},
			//订单状态文字和颜色
			orderStateExp(state) {
				let stateTip = '',
					stateTipColor = '#333';
				switch (+state) {
					case 1:
						stateTip = '等待支付';
						stateTipColor = '#f40';
						break;
					case 2:
						stateTip = '等待卖家发货';
						break;
					case 3:
						stateTip = '卖家已发货';
						break;
					case 4:
						stateTip = '交易成功';
						break;
					case 5:
						stateTip = '交易成功';
						break;
					case 6:
						stateTip = '已完成';
						break;
					case 7:
						stateTip = '订单已关闭';
						stateTipColor = '#777';
						break;
						//更多自定义
				}
				return {
					stateTip,
					stateTipColor
				};
			},
			getRefund(status) {
				return ["退款", "退款中", "待退货", "退款完成", "退款关闭", "退款被拒"][status];
			},
			// 修改地址
			editAddress(id) {
				this.$wanlshop.to('/pages/user/address/address?source=2&order_id=' + id);
			},
			//添加或修改成功之后回调
			async refreshList(address_id, order_id) {
				uni.showLoading({
					title: '正在提交新地址'
				});
				// 获取列表
				await uni.request({
					url: '/wanlshop/order/editOrderAddress',
					method: 'POST',
					data: {
						id: order_id,
						address_id: address_id
					},
					success: res => {
						this.$wanlshop.msg('地址修改成功');
						uni.hideLoading();
					}
				});
			}
		}
	};
</script>

<style>
	page {
		height: 100%;
	}
</style>